﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;

namespace SqlCeCmd
{
    class Program
    {
        static void Main(string[] args)
        {
            string dataSourceString = null;
            string scriptFileName = null;

            for( int i = 0; i < args.Length; i++)
            {
                if (args[i] == "-d") dataSourceString = args[i + 1];
                if (args[i] == "-i") scriptFileName = args[i + 1];
            }

            if (string.IsNullOrEmpty(dataSourceString) ||
                string.IsNullOrEmpty(scriptFileName))
            {
                Console.WriteLine("Sample usage:");
                Console.WriteLine("\tsqlcecmd.exe -d \"DataSource=c:\nw.sdf\" -i \"file.sql\"");
                return;
            }

            string sqlFileContent = ReadFile(scriptFileName);

            ExecuteQuery(dataSourceString, sqlFileContent);
        }

        static string ReadFile(string scriptFileName)
        {
            using (System.IO.StreamReader file =
                new System.IO.StreamReader(scriptFileName))
            {
                return file.ReadToEnd();
            }
        }

        static void ExecuteQuery(string dataSourceString, string queryCommand)
        {
            SqlCeConnection conn = null;

            conn = new SqlCeConnection(dataSourceString);
            conn.Open();
            SqlCeCommand cmd = conn.CreateCommand();

            string[] commands = queryCommand.Split(new string[] { "GO" }, StringSplitOptions.None);
            foreach (string query in commands)
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();
            }
        }

    }
}
